package com.promotores;

import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.content.Context;
import android.util.Log;

import com.promotores.jsonparsing.JSONParser;
import com.promotores.jsonparsing.JSONReader2;
import com.promotores.jsonparsing.JSONReaderListener;
import com.promotores.util.Parametros;

public class JsonPromocion {
	//se llamarían todas las promociones que no tengan created_at ni updated_at
	public void write(List<BeanPromocion> listaPromociones) throws IOException, JSONException{
		for (int i=0; i<listaPromociones.size(); i++){
			JSONObject obj = new JSONObject();
			Date fecha = new Date();
			java.sql.Date fechaSQL = new java.sql.Date(fecha.getTime());
			obj.put("idPromocion", listaPromociones.get(i).getId());
			obj.put("idTipoPromocion", listaPromociones.get(i).getTipoPromocion().getId());
			obj.put("idPromocion", listaPromociones.get(i).getEvento());
			obj.put("fechaInicio", listaPromociones.get(i).getFecIni());
			obj.put("fechaFin", listaPromociones.get(i).getFecFin());
			obj.put("descuento", listaPromociones.get(i).getDescuento());
			obj.put("created_at", fechaSQL);
			obj.put("updated_at", fechaSQL);
			//por terminar 
			FileWriter file = new FileWriter("c:\\test.json");
			file.write(obj.toString());
		}
	}
	
	InputStream is = null;
	String result = "";
	JSONObject jArrayResult = null;
	
	// url to make request
	private static String url = "http://200.16.7.112:3000/promoter_management/promoters/promociones_por_evento/";
			
	// JSON Node names
	private static final String TAG_EVENT_PROMOTION = "event_promotion";
	private static final String TAG_CREATED_AT = "created_at";
	private static final String TAG_UPDATED_AT = "updated_at";
	private static final String TAG_DISCOUNT = "discount";
	private static final String TAG_ID = "id";
	private static final String TAG_EVENT_ID = "event_id";
	private static final String TAG_PROMOTION_ID = "promotion_id";
	private static final String TAG_END_DATE = "end_date";
	private static final String TAG_START_DATE = "start_date";
	private static final String TAG_DIAS = "days";	
	private static final String TAG_DELETED = "deleted";
	
	// contacts JSONArray
	JSONArray promociones = null;
	
	public List<BeanPromocion> read(Context context){
		List<BeanPromocion> lstPromociones = new ArrayList<BeanPromocion>();
				
		// Creating JSON Parser instance
		//JSONParser jParser = new JSONParser();
		String read = url+Parametros.getLast_update()+"(yyyy-MM-dd'T'HH:mm:ss'Z').json";
		//String readValues = jParser.read(read);
		//System.out.println("Json0: "+readValues);
		
		JSONReader2 jReader = new JSONReader2();
		jReader.setJSONReaderListener((JSONReaderListener)context);
		try {
			//JSONArray jsonArray = new JSONArray(readValues);
			JSONArray jsonArray =(jReader.execute(read)).get();
			
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);			
							
				// Storing each json item in variable				
				int id = jsonObject.getJSONObject(TAG_EVENT_PROMOTION).getInt(TAG_ID);
				int event_id = jsonObject.getJSONObject(TAG_EVENT_PROMOTION).getInt(TAG_EVENT_ID);
				int promotion_id = jsonObject.getJSONObject(TAG_EVENT_PROMOTION).getInt(TAG_PROMOTION_ID);
				double descuento = jsonObject.getJSONObject(TAG_EVENT_PROMOTION).getDouble(TAG_DISCOUNT);
				String created_at = jsonObject.getJSONObject(TAG_EVENT_PROMOTION).getString(TAG_CREATED_AT);
				String updated_at = jsonObject.getJSONObject(TAG_EVENT_PROMOTION).getString(TAG_UPDATED_AT);
				String start_date = jsonObject.getJSONObject(TAG_EVENT_PROMOTION).getString(TAG_START_DATE);
				String end_date = jsonObject.getJSONObject(TAG_EVENT_PROMOTION).getString(TAG_END_DATE);
				String days = jsonObject.getJSONObject(TAG_EVENT_PROMOTION).getString(TAG_DIAS);
				//String deleted = jsonObject.getJSONObject(TAG_EVENT_PROMOTION).getString(TAG_DELETED);
				String deleted = "0";
				//falta sacar los dias
				
				BeanTipoPromocion tipo = new BeanTipoPromocion();
				tipo.setId(promotion_id);
				BeanEvento evento = new BeanEvento();
				evento.setId(event_id);
				
				BeanPromocion promocion = new BeanPromocion();
				promocion.setId(id);
				promocion.setEvento(evento);
				promocion.setTipoPromocion(tipo);
				promocion.setFecIni(start_date.replace("-","/"));
				promocion.setFecFin(end_date.replace("-","/"));
				promocion.setDias(days);
				promocion.setDescuento(descuento);
				promocion.setCreated_at(created_at);
				promocion.setUpdated_at(updated_at);
				promocion.setDeleted(deleted);
				promocion.setSaved("1");
				lstPromociones.add(promocion);
			}
		} catch (Exception e) {
			System.out.println("Json: Exception");
			e.printStackTrace();
			return null;
		}
		return lstPromociones;
	}
	
	public BeanPromocionResponse postData(BeanPromocion promocion)throws IOException, JSONException {
	    // Create a new HttpClient and Post Header
		String url2 = "http://200.16.7.112:3000/promoter_management/promotions/create_event_promotions/";
	    HttpParams myParams = new BasicHttpParams();
	    HttpConnectionParams.setConnectionTimeout(myParams, 10000);
	    HttpConnectionParams.setSoTimeout(myParams, 10000);
	    HttpClient httpclient = new DefaultHttpClient( myParams);
//	    String json=obj.toString();
	    int id=0;
	    String updated_at="";
	    String created_at="";
	    BeanPromocionResponse promoResponse = new BeanPromocionResponse();

	    try {

	        HttpPost httppost = new HttpPost(url2.toString());
	        httppost.setHeader("Content-type", "application/json");
	       
	        	JSONObject event_promotion = new JSONObject();	
	        	JSONObject obj = new JSONObject();
				Date fecha = new Date();
				java.sql.Date fechaSQL = new java.sql.Date(fecha.getTime());
//				obj.put(TAG_ID, listaPromociones.getId());
				
				obj.put(TAG_PROMOTION_ID, promocion.getTipoPromocion().getId());
				obj.put(TAG_EVENT_ID, promocion.getEvento().getId());
				obj.put(TAG_START_DATE, promocion.getFecIni());
				obj.put(TAG_END_DATE, promocion.getFecFin());
				obj.put(TAG_DISCOUNT, promocion.getDescuento());
				obj.put(TAG_DIAS, promocion.getDias());
				//obj.put(TAG_CREATED_AT, fechaSQL);
				//obj.put(TAG_UPDATED_AT, fechaSQL);
				//obj.put(TAG_DELETED,promocion.getDeleted());
				event_promotion.put(TAG_EVENT_PROMOTION, obj);

			StringEntity se = new StringEntity(event_promotion.toString()); 
	        httppost.setEntity(se);
	        httppost.setHeader("Accept", "application/json");
			httppost.setHeader("Content-Type", "application/json");

	        HttpResponse httpResponse = httpclient.execute(httppost);	        
	        HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();           
 
	        } catch (UnsupportedEncodingException e) {
	            e.printStackTrace();
	            return null;
	        } catch (ClientProtocolException e) {
	            e.printStackTrace();
	            return null;
	        } catch (IOException e) {
	            e.printStackTrace();
	            return null;
	        } catch (JSONException e) {
				e.printStackTrace();
				return null;
			}
	 
	        try {
	            BufferedReader reader = new BufferedReader(new InputStreamReader(
	                    is, "iso-8859-1"), 8);
	            StringBuilder sb = new StringBuilder();
	            String line = null;
	            while ((line = reader.readLine()) != null) {
	                sb.append(line + "\n");
	            }
	            is.close();
	            result = sb.toString();
	        } catch (Exception e) {
	            Log.e("Buffer Error", "Error converting result " + e.toString());
	            return null;
	        }
	 
	        // try parse the string to a JSON object
	        try {
	        	jArrayResult = new JSONObject(result);
	        	System.out.println("ojb:"+jArrayResult);
	        	//int id = jArrayResult.getJSONObject(TAG_EVENT_PROMOTION).getInt(TAG_ID);
	        	//int id = jArrayResult.getInt(TAG_ID);
	        	JSONObject json = jArrayResult.getJSONObject(TAG_EVENT_PROMOTION);
	        	System.out.println("json:"+json);
	        	id = json.getInt(TAG_ID);
	        	updated_at=json.getString(TAG_UPDATED_AT);
	        	created_at=json.getString(TAG_CREATED_AT);
	        	promoResponse.setId(id);
	        	promoResponse.setUpdated_at(updated_at);
	        	promoResponse.setCreated_at(created_at);
	        	//return id;
	        } catch (JSONException e) {
	            Log.e("JSON Parser", "Error parsing data " + e.toString());
	            //return 0;
	        } finally {
	        	return promoResponse;
	        }
	} 
	    
		public int postDeleted(int idPromocion)throws IOException, JSONException {
	        // Create a new HttpClient and Post Header
	       String url3 = "http://200.16.7.112:3000/promoter_management/promotions/delete_event_promotion/";
	       HttpParams  myParams = new BasicHttpParams();
		    HttpConnectionParams.setConnectionTimeout(myParams, 10000);
		    HttpConnectionParams.setSoTimeout(myParams, 10000);
		    HttpClient httpclient = new DefaultHttpClient( myParams);
		//   String json=obj.toString();

		    try {
		
		        HttpPost httppost = new HttpPost(url3.toString());
		        //httppost.setHeader("Content-type", "application/json");
	            //JSONObject event = new JSONObject();
	            JSONObject obj = new JSONObject();

	            obj.put("idpromocionxevento", idPromocion);
	            
	            StringEntity se = new StringEntity(obj.toString());
		        httppost.setEntity(se);
		        httppost.setHeader("Accept", "application/json");
				httppost.setHeader("Content-Type", "application/json");
		
		        HttpResponse httpResponse = httpclient.execute(httppost);
		        HttpEntity httpEntity = httpResponse.getEntity();
	            is = httpEntity.getContent();           
	 
		        } catch (UnsupportedEncodingException e) {
		            e.printStackTrace();
		            return 0;
		        } catch (ClientProtocolException e) {
		            e.printStackTrace();
		            return 0;
		        } catch (IOException e) {
		            e.printStackTrace();
		            return 0;
		        } catch (JSONException e) {
					e.printStackTrace();
					return 0;
				}
		 
		        try {
		            BufferedReader reader = new BufferedReader(new InputStreamReader(
		                    is, "iso-8859-1"), 8);
		            StringBuilder sb = new StringBuilder();
		            String line = null;
		            while ((line = reader.readLine()) != null) {
		                sb.append(line + "\n");
		            }
		            is.close();
		            result = sb.toString();
		        } catch (Exception e) {
		            Log.e("Buffer Error", "Error converting result " + e.toString());
		            return 0;
		        }
		 
		        // try parse the string to a JSON object
		        try {
		        	jArrayResult = new JSONObject(result);
//		        	int id = jArrayResult.getJSONObject(TAG_EVENT_PROMOTION).getInt(TAG_ID);
//		        	System.out.println("id:" + id);
//		        	return id;
		        	return 1;
		        } catch (JSONException e) {
		            Log.e("JSON Parser", "Error parsing data " + e.toString());
		            return 0;
		        }
		}
}
